<script setup>
import {onMounted, ref, watch} from 'vue';
import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag
} from 'element-plus';
import http from "@/request/http.js";
import {useRoute} from "vue-router";

const route = useRoute();

// 基础状态
const isLoading = ref(false);
const banList = ref([]);
const detailDialogVisible = ref(false);
const currentBanRecord = ref(null);

// 搜索表单（增加封禁类型筛选）
const searchForm = ref({
  articleId: '',
  banReason: '',
  isProcessed: null,
  banType: '' // 封禁类型筛选
});

// 分页参数
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
  pages: 0
});

// 时间格式化
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 封禁类型转显示文本
const getBanTypeText = (type) => {
  const typeMap = {
    'SYSTEM_BAN': '系统封禁',
    'VIOLATION_BAN': '违规封禁',
    'COPYRIGHT_BAN': '版权封禁'
  };
  return typeMap[type] || (type || '未知类型');
};

// 封禁类型转标签样式
const getBanTypeTagType = (type) => {
  const typeStyleMap = {
    'SYSTEM_BAN': 'danger',    // 系统封禁-红色
    'VIOLATION_BAN': 'warning', // 违规封禁-橙色
    'COPYRIGHT_BAN': 'info'     // 版权封禁-蓝色
  };
  return typeStyleMap[type] || 'default';
};

// 表格行样式（未处理行高亮）
const tableRowClassName = ({row}) => {
  return row.isProcessed === 0 ? 'unprocessed-row' : '';
};

// 获取封禁记录列表
const fetchBanList = async () => {
  isLoading.value = true;
  try {
    const params = {
      currentPage: pagination.value.current,
      pageSize: pagination.value.size,
      articleId: searchForm.value.articleId || null,
      articleBanReason: searchForm.value.banReason,
      isProcessed: searchForm.value.isProcessed !== null ? Number(searchForm.value.isProcessed) : null,
      articleBanType: searchForm.value.banType || null // 增加封禁类型筛选参数
    };

    const response = await http.get('/system/articleBan/banArticleList', {params});

    if (response?.code === 200 && response?.data) {
      // 雪花ID转为字符串处理
      const records = response.data.records || [];
      banList.value = records.map(item => ({
        ...item,
        abanId: item.abanId?.toString() || '',
        articleId: item.articleId?.toString() || '',
        isProcessed: item.isProcessed || 0,
        unbanReason: item.unbanReason || ''
      }));

      pagination.value = {
        ...pagination.value,
        total: response.data.total || 0,
        pages: response.data.pages || 0,
        current: response.data.current || 1,
        size: response.data.size || 10
      };
    } else {
      ElMessage.error(`获取封禁记录失败：${response?.msg || '未知错误'}`);
    }
  } catch (error) {
    ElMessage.error('网络错误，无法加载封禁记录');
    console.error('封禁列表请求异常：', error);
  } finally {
    isLoading.value = false;
  }
};

// 搜索重置
const resetSearch = () => {
  searchForm.value = {
    articleId: '',
    banReason: '',
    isProcessed: null,
    banType: ''
  };
  pagination.value.current = 1;
  fetchBanList();
};

// 分页事件
const handleSizeChange = (val) => {
  pagination.value.size = val;
  pagination.value.current = 1;
  fetchBanList();
};

const handleCurrentChange = (val) => {
  pagination.value.current = val;
  fetchBanList();
};

// 查看详情
const viewBanDetail = (row) => {
  currentBanRecord.value = row;
  detailDialogVisible.value = true;
};

// 监听路由变化刷新数据
watch(
    () => route.fullPath,
    () => fetchBanList()
);

// 初始化加载
onMounted(() => {
  fetchBanList();
});
</script>

<template>
  <div class="ban-page">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="文章ID">
          <el-input
              v-model="searchForm.articleId"
              clearable
              placeholder="请输入文章ID"
              style="width: 180px"
              type="text"
          />
        </el-form-item>
        <el-form-item label="封禁原因">
          <el-input
              v-model="searchForm.banReason"
              clearable
              placeholder="请输入封禁原因关键词"
              style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select
              v-model="searchForm.isProcessed"
              clearable
              placeholder="请选择处理状态"
              style="width: 180px"
          >
            <el-option label="未处理" value="0"/>
            <el-option label="已处理" value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="封禁类型">
          <el-select
              v-model="searchForm.banType"
              clearable
              placeholder="请选择封禁类型"
              style="width: 180px"
          >
            <el-option label="系统封禁" value="SYSTEM_BAN"/>
            <el-option label="违规封禁" value="VIOLATION_BAN"/>
            <el-option label="版权封禁" value="COPYRIGHT_BAN"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchBanList">搜索</el-button>
          <el-button style="margin-left: 8px" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 封禁列表表格 -->
    <el-table
        v-loading="isLoading"
        :data="banList"
        border
        loading-text="加载中..."
        stripe
        style="width: 100%; margin-top: 16px"
        :row-class-name="tableRowClassName"
    >
      <el-table-column align="center" label="序号" type="index" width="80"/>
      <el-table-column align="center" label="文章ID" prop="articleId" width="200"/>
      <el-table-column align="center" label="处理状态" prop="isProcessed" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.isProcessed === 0" type="warning">未处理</el-tag>
          <el-tag v-else type="success">已处理</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="封禁类型" prop="articleBanType" width="120">
        <template #default="scope">
          <el-tag
              :type="getBanTypeTagType(scope.row.articleBanType)"
              class="custom-ban-tag"
          >
            {{ getBanTypeText(scope.row.articleBanType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="封禁原因" min-width="220" prop="articleBanReason">
        <template #default="scope">
          <div :title="scope.row.articleBanReason" class="reason-ellipsis">
            {{ scope.row.articleBanReason || '未填写' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="封禁时间" prop="banTime" width="180">
        <template #default="scope">
          {{ scope.row.banTime ? formatTime(scope.row.banTime) : '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="解封原因" min-width="220" prop="unbanReason">
        <template #default="scope">
          <div :title="scope.row.unbanReason" class="reason-ellipsis">
            {{ scope.row.unbanReason || (scope.row.isProcessed === 1 ? '无原因' : '未解封') }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="解封时间" prop="processedTime" width="180">
        <template #default="scope">
          {{
            scope.row.processedTime ? formatTime(scope.row.processedTime) : (scope.row.isProcessed === 1 ? '未知时间' : '未解封')
          }}
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="100">
        <template #default="scope">
          <el-button
              color="primary"
              type="text"
              @click="viewBanDetail(scope.row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-group">
      <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50]"
          :total="pagination.total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 20px; text-align: right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 封禁详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        :close-on-click-modal="false"
        title="封禁详情"
        width="600px"
    >
      <div v-if="currentBanRecord" class="detail-content">
        <div class="detail-item">
          <span class="detail-label">封禁记录ID：</span>
          <span class="detail-value">{{ currentBanRecord.abanId }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">文章ID：</span>
          <span class="detail-value">{{ currentBanRecord.articleId }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">处理状态：</span>
          <span class="detail-value">
            <el-tag v-if="currentBanRecord.isProcessed === 0" type="warning">未处理</el-tag>
            <el-tag v-else type="success">已处理</el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="detail-label">封禁类型：</span>
          <span class="detail-value">
            <el-tag
                :type="getBanTypeTagType(currentBanRecord.articleBanType)"
                class="custom-ban-tag"
            >
              {{ getBanTypeText(currentBanRecord.articleBanType) }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="detail-label">封禁原因：</span>
          <span class="detail-value">{{ currentBanRecord.articleBanReason || '未填写' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">封禁时间：</span>
          <span class="detail-value">{{
              currentBanRecord.banTime ? formatTime(currentBanRecord.banTime) : '未知'
            }}</span>
        </div>
        <div v-if="currentBanRecord.isProcessed === 1" class="detail-item">
          <span class="detail-label">解封原因：</span>
          <span class="detail-value">{{ currentBanRecord.unbanReason || '无原因' }}</span>
        </div>
        <div v-if="currentBanRecord.isProcessed === 1" class="detail-item">
          <span class="detail-label">解封时间：</span>
          <span class="detail-value">{{
              currentBanRecord.processedTime ? formatTime(currentBanRecord.processedTime) : '未知时间'
            }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.ban-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #333;
}

.page-header p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.search-bar {
  margin-bottom: 16px;
}

.search-form {
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

/* 表格行样式 */
:deep(.unprocessed-row) {
  background-color: #fff8e6 !important; /* 未处理行浅黄色背景 */
}

.reason-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

/* 自定义封禁类型标签样式 */
.custom-ban-tag {
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 12px;
  height: auto;
  line-height: 1.5;
}

.detail-content {
  padding: 10px 0;
}

.detail-item {
  margin-bottom: 12px;
  line-height: 1.6;
}

.detail-label {
  display: inline-block;
  width: 100px;
  font-weight: 600;
  color: #333;
}

.detail-value {
  color: #666;
  word-break: break-all;
}

.pagination-group {
  margin-top: 16px;
}

/* 雪花ID展示优化 */
:deep(.el-table__cell) {
  white-space: normal;
  word-break: break-all;
  vertical-align: middle;
}

/* 表格空状态样式 */
:deep(.el-table__empty-text) {
  padding: 40px 0;
}
</style>